import request from "./request";
import { requestWithAuth } from "./request";
import { ElMessage } from "element-plus";
import cache from "@/utils/cache";

const CACHE_KEY = {
  ROLE_LIST: "role_list",
  ROLE_DETAIL: "role_detail_",
};

const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

/**
 * 统一的错误处理
 * @param {Error} error - 错误对象
 * @param {string} customMessage - 自定义错误消息
 */
const handleError = (error, customMessage = "操作失败") => {
  console.error(error);
  ElMessage.error(customMessage);
  throw error;
};

/**
 * 获取角色列表
 * @returns {Promise} - 返回角色列表数据
 */
export async function getRoles() {
  try {
    const response = await requestWithAuth({
      url: "/Role/list",
      method: "get",
    });

    // 确保返回的是数组
    const roles = Array.isArray(response.data.data) ? response.data : [];
    return { data: roles };
  } catch (error) {
    handleError(error, "获取角色列表失败");
    return { data: [] }; // 发生错误时返回空数组
  }
}

/**
 * 获取单个角色信息
 * @param {number} id - 角色ID
 * @returns {Promise} - 返回角色信息
 */
export async function getRole(id) {
  try {
    if (!id) throw new Error("角色ID不能为空");

    // 检查缓存
    const cacheKey = `${CACHE_KEY.ROLE_DETAIL}${id}`;
    const cachedData = cache.get(cacheKey);
    if (cachedData) {
      return cachedData;
    }

    const response = await requestWithAuth({
      url: `/Role/detail/${id}`,
      method: "get",
    });

    cache.set(cacheKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取角色详情失败");
  }
}

/**
 * 创建新角色
 * @param {Object} roleData - 新角色的数据
 * @returns {Promise} - 返回创建操作的结果
 */
export const createRole = async (roleData) => {
  try {
    if (!roleData.roleName) {
      throw new Error("角色名称不能为空");
    }

    const response = await requestWithAuth({
      url: "/Role/create",
      method: "POST",
      data: roleData,
    });

    // 清除列表缓存
    cache.removeByPrefix(CACHE_KEY.ROLE_LIST);

    return response;
  } catch (error) {
    handleError(error, "创建角色失败");
  }
};

/**
 * 更新角色信息
 * @param {Object} roleData - 更新的角色数据
 * @returns {Promise} - 返回更新操作的结果
 */
export const updateRole = async (roleData) => {
  try {
    if (!roleData.roleId) {
      throw new Error("角色ID不能为空");
    }
    if (!roleData.roleName) {
      throw new Error("角色名称不能为空");
    }

    const response = await requestWithAuth({
      url: `/Role/update/${roleData.roleId}`,
      method: "PUT",
      data: roleData,
    });

    // 清除相关缓存
    cache.removeByPrefix(CACHE_KEY.ROLE_LIST);
    cache.remove(`${CACHE_KEY.ROLE_DETAIL}${roleData.roleId}`);

    return response;
  } catch (error) {
    handleError(error, "更新角色信息失败");
  }
};

/**
 * 删除角色
 * @param {number} id - 要删除的角色ID
 * @returns {Promise} - 返回删除操作的结果
 */
export const deleteRole = async (id) => {
  try {
    if (!id) throw new Error("角色ID不能为空");

    const response = await requestWithAuth({
      url: `/Role/${id}`,
      method: "DELETE",
    });

    // 清除相关缓存
    cache.removeByPrefix(CACHE_KEY.ROLE_LIST);
    cache.remove(`${CACHE_KEY.ROLE_DETAIL}${id}`);

    return response;
  } catch (error) {
    handleError(error, "删除角色失败");
  }
};

/**
 * 获取角色的菜单权限
 * @param {number} roleId - 角色ID
 * @returns {Promise} - 返回该角色的菜单ID列表
 */
export const getRoleMenus = async (roleId) => {
  try {
    if (!roleId) throw new Error("角色ID不能为空");

    const response = await requestWithAuth({
      url: `/Role/MenuPermissions`,
      method: "get",
      params: { roleId },
    });

    // 处理返回的数据结构
    if (response.status === 200) {
      // 检查 response.data 中的数组
      const menuIds = response.data.data || response.data;
      if (Array.isArray(menuIds)) {
        return { data: menuIds };
      }

      // 如果 data 是对象且包含数组数据
      if (menuIds && Array.isArray(Object.values(menuIds))) {
        const ids = Object.values(menuIds).filter(
          (value) => typeof value === "number" || typeof value === "string"
        );
        return { data: ids };
      }
    }

    return { data: [] };
  } catch (error) {
    handleError(error, "获取角色菜单权限失败");
    return { data: [] };
  }
};

/**
 * 保存角色的菜单权限
 * @param {number} roleId - 角色ID
 * @param {Array} menus - 菜单ID数组
 * @returns {Promise} - 返回保存结果
 */
export const saveRoleMenus = async (roleId, menus) => {
  try {
    if (!roleId) throw new Error("角色ID不能为空");
    if (!Array.isArray(menus)) throw new Error("菜单ID列表格式错误");

    // 根据 AssignRoleModel 的要求构造数据
    const response = await requestWithAuth({
      url: "/Role/assignMenuPermissions",
      method: "post",
      data: {
        roleId: roleId,
        menus: menus,
      },
    });

    return response;
  } catch (error) {
    handleError(error, "保存角色菜单权限失败");
  }
};
